package com.zlf.service;

import com.zlf.feign.CartFeignClient;
import com.zlf.mapper.OrderDetailetMapper;
import com.zlf.mapper.OrdersMapper;
import com.zlf.po.Cart;
import com.zlf.po.CommonResult;
import com.zlf.po.OrderDetailet;
import com.zlf.po.Orders;
import com.zlf.util.CommonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class OrdersServiceImpl implements OrdersService {

    @Qualifier("com.zlf.feign.CartFeignClient")
    @Autowired
    private CartFeignClient cartFeignClient;

    @Autowired
    private OrdersMapper ordersMapper;

    @Autowired
    private OrderDetailetMapper orderDetailetMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int createOrders(Orders orders) throws Exception {
        // 1、查询当前用户购物车中当前商家的所有食品
        Cart cart = new Cart();
        cart.setUserId(orders.getUserId());
        cart.setBusinessId(orders.getBusinessId());

        CommonResult<List> result = cartFeignClient.listCart(cart.getUserId(), cart.getBusinessId());
        if (result.getCode() == 403) {
            return -403;
        }

        List<Cart> cartList = result.getResult();
        if (cartList == null || cartList.isEmpty()) {
            throw new IllegalArgumentException("购物车为空，无法创建订单");
        }

        // 2、创建订单（返回生成的订单编号）
        orders.setOrderDate(CommonUtil.getCurrentDate());
        ordersMapper.saveOrders(orders);
        int orderId = orders.getOrderId();

        // 3、批量添加订单明细
        List<OrderDetailet> orderDetails = new ArrayList<>();
        for (Object item : cartList) {
            try {
                Map<String, Object> map = (Map<String, Object>) item;
                OrderDetailet od = new OrderDetailet();
                od.setOrderId(orderId);
                od.setFoodId(Integer.parseInt(map.get("foodId").toString()));
                od.setQuantity(Integer.parseInt(map.get("quantity").toString()));
                orderDetails.add(od);
            } catch (Exception e) {
                throw new RuntimeException("转换购物车项到订单明细时出错", e);
            }
        }

        if (!orderDetails.isEmpty()) {
            orderDetailetMapper.saveOrderDetailetBatch(orderDetails);
        } else {
            throw new RuntimeException("没有有效的订单明细可以保存");
        }

        // 4、从购物车表中删除相关食品信息
        CommonResult result_d = cartFeignClient.cleanCart(cart.getUserId(), cart.getBusinessId());
        if (result_d.getCode() == 403) {
            throw new RuntimeException("清理购物车失败: 权限不足");
        }

        return orderId;
    }

    // 其他方法保持不变...
    @Override
    public Orders getOrdersById(Integer orderId) {
        return ordersMapper.getOrdersById(orderId);
    }

    @Override
    public List<Orders> listOrdersByUserId(String userId) {
        return ordersMapper.listOrdersByUserId(userId);
    }

    @Override
    public int payOrdersById(Integer orderId) {
        return ordersMapper.payOrdersById(orderId);
    }

    @Override
    public int cancelOrdersById(Integer orderId) {
        return ordersMapper.cancelOrdersById(orderId);
    }

    @Override
    public List<Orders> listOrdersByUserIdByState(String userId, int orderState) {
        return ordersMapper.listOrdersByUserIdByState(userId, orderState);
    }
}